package com.platform.cdcs.fragment.operation;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.platform.cdcs.R;
import com.platform.cdcs.adapter.SimpleItemAdapter;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.ViewTool;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.fragment.SearchListener;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * Created by holytang on 2017/10/6.
 */
public class OperationSearchFragment extends BaseFragment {
    private ObservableXListView slideListView;
    private ItemAdapter adapter;
    private String mclass;
    private List<ChooseItem> sourceList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mclass = getArguments().getString("class");
        adapter = new ItemAdapter(getContext());
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle("选择手术类型");
        view.findViewById(R.id.search_layout).setVisibility(View.VISIBLE);
        initSearch(view.findViewById(R.id.search), "输入手术类型搜索", new SearchListener() {
            @Override
            public void search(String s) {
                if(TextUtils.isEmpty(s)){
                    adapter.clear();
                    adapter.addAll(sourceList);
                    adapter.notifyDataSetChanged();
                }else{
                    List<ChooseItem> mList=new ArrayList<ChooseItem>();
                    adapter.clear();
                    for(ChooseItem item:sourceList){
                        if(item.getTitle().contains(s)){
                            mList.add(item);
                        }
                    }
                    adapter.addAll(mList);
                    adapter.notifyDataSetChanged();
                }
            }
        }, view.findViewById(R.id.cancel));

        slideListView = (ObservableXListView) view.findViewById(android.R.id.list);
        slideListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestData(false);
            }

            @Override
            public void onLoadMore() {

            }
        });
        slideListView.setAdapter(adapter);
        slideListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ChooseItem item = (ChooseItem) adapterView.getItemAtPosition(i);
                if (item != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("name", item.getTitle());
                    RefershEvent event = new RefershEvent();
                    event.bundle = bundle;
                    try {
                        event.mclass = Class.forName(mclass);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    event.oclass = OperationSearchFragment.this.getClass();
                    EventBus.getDefault().post(event);
                    getActivity().finish();
                }
            }
        });
        requestData(true);
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestData(boolean show) {
        if (show) {
            showLoadImg();
        }
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "1");
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                slideListView.stopRefresh();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                slideListView.stopRefresh();
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        sourceList=new ArrayList<ChooseItem>();
                        JSONArray jsonArray = obj.getJSONArray("surList");
                        for (int j = 0; j < jsonArray.length(); j++) {
                            String name = jsonArray.getString(j);
                            if (!name.contains("请选择")) {
                                ChooseItem item = new ChooseItem();
                                item.setTitle(name);
                                sourceList.add(item);
                            }
                        }
                        adapter.addAll(sourceList);
                        adapter.notifyDataSetChanged();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                }
            }
        });
    }

    private class ItemAdapter extends EnhancedAdapter<ChooseItem> {

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            holder.titleView.setText(getItem(position).getTitle());
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = inflater.inflate(R.layout.left_right, viewgroup, false);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            rootView.setTag(holder);
            return rootView;
        }
    }

    private class ViewHolder {
        TextView titleView;
    }
}
